package org.road0329.dlt698;

import java.io.ByteArrayOutputStream;

public class ReverseByteArrayOutputStream extends ByteArrayOutputStream {
    private boolean automaticResize = false;

    public ReverseByteArrayOutputStream() {
        super();
    }

    public void setBufSize(int bufferSize) {
        this.buf = new byte[bufferSize];
        this.count = bufferSize;
        this.automaticResize = false;
    }

    public void setBufSizeResize(int bufferSize, boolean automaticResize) {
        this.buf = new byte[bufferSize];
        this.count = bufferSize;
        this.automaticResize = automaticResize;
    }

    public void setBuf(byte[] buffer) {
        this.buf = buffer;
        this.count = buffer.length;
        this.automaticResize = false;
    }

    public void setBufIndex(byte[] buffer, int index) {
        this.buf = buffer;
        this.count = index;
        this.automaticResize = false;
    }

    public void setBufIndexResize(byte[] buffer, int index, boolean automaticResize) {
        this.buf = buffer;
        this.count = index;
        this.automaticResize = automaticResize;
    }

    public void writeByte(byte[] byteArray) {
        for (int i = byteArray.length - 1; i >= 0; i--) {
            write(byteArray[i]);
        }
    }

    @Override
    public synchronized void write(int b) {
        if (count == 0) {
            if (automaticResize) {
                resize();
            } else {
                throw new RuntimeException("Buffer is full");
            }
        }
        buf[--count] = (byte) b;
    }

    private void resize() {
        byte[] newBuf = new byte[buf.length * 2];
        System.arraycopy(buf, 0, newBuf, buf.length, buf.length);
        buf = newBuf;
        count += buf.length / 2;
    }

    public byte[] getArray() {
        if (count == buf.length) {
            return buf;
        }
        byte[] subBuffer = new byte[buf.length - count];
        System.arraycopy(buf, count, subBuffer, 0, subBuffer.length);
        return subBuffer;
    }

    @Override
    public void reset() {
        count = buf.length;
    }
}



